package main

import (
	"context"
	"flag"
	"fmt"
	"net/http"
	"strings"

	"oil-station-backend/internal/config"
	"oil-station-backend/internal/handler/admin"
	"oil-station-backend/internal/handler/auth"
	"oil-station-backend/internal/handler/fuel"
	"oil-station-backend/internal/handler/order"
	"oil-station-backend/internal/handler/payment"
	"oil-station-backend/internal/svc"

	"github.com/golang-jwt/jwt/v4"
	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/rest"
)

var configFile = flag.String("f", "etc/oil-station-api.yaml", "the config file")

func main() {

	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)

	server := rest.MustNewServer(c.RestConf)
	defer server.Stop()

	ctx := svc.NewServiceContext(c)
	
	// 注册路由
	registerHandlers(server, ctx)

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}

func registerHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
	// 认证相关路由
	server.AddRoute(rest.Route{
		Method:  http.MethodPost,
		Path:    "/api/auth/login",
		Handler: auth.LoginHandler(serverCtx),
	})
	
	server.AddRoute(rest.Route{
		Method:  http.MethodPost,
		Path:    "/api/auth/wechat/login",
		Handler: auth.WechatLoginHandler(serverCtx),
	})
	
	// 微信支付回调（不需要JWT认证）
	server.AddRoute(rest.Route{
		Method:  http.MethodPost,
		Path:    "/api/payment/wechat/notify",
		Handler: payment.WechatPayNotifyHandler(serverCtx),
	})

	// 创建自定义JWT中间件
	jwtMiddleware := func(next http.HandlerFunc) http.HandlerFunc {
		return func(w http.ResponseWriter, r *http.Request) {
			// 从Authorization header获取token
			authHeader := r.Header.Get("Authorization")
			if authHeader == "" || len(authHeader) <= 7 || !strings.HasPrefix(authHeader, "Bearer ") {
				http.Error(w, "未授权：缺少有效的Authorization头", http.StatusUnauthorized)
				return
			}

			// 提取token
			tokenString := authHeader[7:] // 去掉"Bearer "前缀

			// 解析token
			claims := jwt.MapClaims{}
			token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
				// 验证签名方法
				if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
					return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
				}
				return []byte(serverCtx.Config.Auth.AccessSecret), nil
			})

			if err != nil || !token.Valid {
				http.Error(w, "未授权：无效的token", http.StatusUnauthorized)
				return
			}

			// 将claims添加到context中
			ctx := context.WithValue(r.Context(), "claims", claims)
			
			// 同时也添加userInfo到context中，方便直接获取
			userInfo := map[string]interface{}{
				"id":       claims["id"],
				"username": claims["username"],
				"openId":   claims["openId"],
				"role":     claims["role"],
			}
			ctx = context.WithValue(ctx, "userInfo", userInfo)

			// 使用新的context继续处理请求
			next(w, r.WithContext(ctx))
		}
	}

	// 需要JWT认证的路由组
	jwtRoutes := []rest.Route{
		{
			Method:  http.MethodGet,
			Path:    "/api/fuel/types",
			Handler: fuel.GetFuelTypesHandler(serverCtx),
		},
		{
			Method:  http.MethodPost,
			Path:    "/api/fuel/order",
			Handler: fuel.CreateOrderHandler(serverCtx),
		},
		{
			Method:  http.MethodGet,
			Path:    "/api/order/list",
			Handler: order.GetOrderListHandler(serverCtx),
		},
		{
			Method:  http.MethodGet,
			Path:    "/api/order/:id",
			Handler: order.GetOrderDetailHandler(serverCtx),
		},
		{
			Method:  http.MethodPost,
			Path:    "/api/order/complete",
			Handler: order.CompleteOrderHandler(serverCtx),
		},
		{
			Method:  http.MethodPost,
			Path:    "/api/payment/wechat/pay",
			Handler: payment.WechatPayHandler(serverCtx),
		},
		{
			Method:  http.MethodPost,
			Path:    "/api/payment/create",
			Handler: payment.CreatePaymentOrderHandler(serverCtx),
		},
	}
	
	for _, route := range jwtRoutes {
		// 使用自定义JWT中间件替代rest.WithJwt
		server.AddRoute(rest.Route{
			Method:  route.Method,
			Path:    route.Path,
			Handler: jwtMiddleware(route.Handler),
		})
	}

	// 管理员路由组
	adminRoutes := []rest.Route{
		{
			Method:  http.MethodPost,
			Path:    "/api/admin/fuel/price",
			Handler: admin.UpdateFuelPriceHandler(serverCtx),
		},
		{
			Method:  http.MethodGet,
			Path:    "/api/admin/inventory",
			Handler: admin.GetInventoryHandler(serverCtx),
		},
		{
			Method:  http.MethodPost,
			Path:    "/api/admin/inventory",
			Handler: admin.UpdateInventoryHandler(serverCtx),
		},
		{
			Method:  http.MethodGet,
			Path:    "/api/admin/report/sales",
			Handler: admin.GetSalesReportHandler(serverCtx),
		},
	}
	
	// 管理员路由需要JWT认证和管理员权限
	adminMiddleware := func(next http.HandlerFunc) http.HandlerFunc {
		return func(w http.ResponseWriter, r *http.Request) {
			// 先进行JWT认证
			jwtHandler := jwtMiddleware(func(w http.ResponseWriter, r *http.Request) {
				// JWT认证通过后，检查是否有管理员权限
				claims := r.Context().Value("claims").(jwt.MapClaims)
				role, ok := claims["role"].(string)
				if !ok || role != "admin" {
					http.Error(w, "无权访问：需要管理员权限", http.StatusForbidden)
					return
				}
				
				// 有管理员权限，继续处理请求
				next(w, r)
			})
			
			// 执行JWT认证
			jwtHandler(w, r)
		}
	}
	
	for _, route := range adminRoutes {
		// 使用管理员中间件
		server.AddRoute(rest.Route{
			Method:  route.Method,
			Path:    route.Path,
			Handler: adminMiddleware(route.Handler),
		})
	}
}

